package com.softhinker.ke24.unit3.engine;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import com.softhinker.ke24.unit3.model.Stock;

public class Database {
	private Map<String, Stock> stocks = new HashMap<String, Stock>();
	private List<Stock> stockList = new ArrayList<Stock>();
	
	public Database(){
		loadData();
	}
	
	protected void loadData(){
		try {
			InputStream is = this.getClass().getResourceAsStream("Stocks.xls");
			HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
			Sheet sheet1 = wb.getSheetAt(0);
			
			for (Row row : sheet1){
				if(row.getRowNum() == 0){
					continue;
				}
				
				Cell cell0 = row.getCell(0);
				Cell cell1 = row.getCell(1);
				Cell cell2 = row.getCell(2);
				
				if(cell0 == null && cell1 == null && cell2 == null){
					break;
				}
				
				String code1 = "";
				if(Cell.CELL_TYPE_NUMERIC == cell1.getCellType()){
					code1 = String.valueOf((int)cell1.getNumericCellValue());
				} else{
					code1 = cell1.getStringCellValue();
				}
				Stock stock = new Stock("");
				stock.setCounterName(cell0 == null ? "" : cell0.getStringCellValue());
				stock.setCode(code1);
				stock.setBackground(cell2 == null ? "" : cell2.getStringCellValue());
				
				stocks.put(stock.getCode(), stock);
				stockList.add(stock);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Map<String, Stock> getStocks(){
		return this.stocks;
	}
	
	public List<Stock> getStockList(){
		return this.stockList;
	}
}
